package com.springboot2.security.base.security.service;

import com.springboot2.security.entity.po.RoleInfo;
import com.springboot2.security.entity.po.UserInfo;
import com.springboot2.security.mappers.user.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 获取用户信息和权限返回
 * org.springframework.security.core.userdetails.User;
 *
 * @param
 * @author liucancan
 * @date 13:55 2018/12/12
 * @return
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userRepository;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 获取登录人用户信息
        UserInfo user = userRepository.findByUsername(userName);
        // 获取用户所有权限
        Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
        // 封装成spring security的user返回
        return new User(user.getUserName(), user.getPassword(), grantedAuths);
    }

    /**
     * 组织用户拥有哪些角色
     * 组织GrantedAuthority集合, 可以放角色名称或权限标志，这里角色名称，资源鉴权时就根据角色名称判断用户有没有权限访问资源
     *
     * @param
     * @return
     * @date 16:17 2018/12/13
     */
    private Set<GrantedAuthority> obtionGrantedAuthorities(UserInfo user) {
        Set<RoleInfo> roles = user.getRoles();
        Set<GrantedAuthority> authSet = new HashSet<>();
        for (RoleInfo role : roles) {
            authSet.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authSet;
    }
}
